import path from 'path';
import matter from 'gray-matter';
import fs from 'fs';
import fg from 'fast-glob'
import _ from 'lodash'
import { PostMeta } from 'interface/post';
import { md } from './markdown';
import dayjs from 'dayjs';

export const getPosts = async () => {
  const filePaths = await fg(['posts/**/*.md'])
  const posts = [] as PostMeta[]
  filePaths.forEach(filePath => {
    const fullPath = path.join(process.cwd(), filePath);
    const id = getPostId(fullPath)
    const text = fs.readFileSync(fullPath, 'utf-8');
    const { data: { title, date, about } } = matter(text);
    if (about) {
      return
    }
    posts.push({
      id, title, date: date ? new Date(date).getTime() : null
    })
  });

  const orderPosts = _.orderBy(posts, ['date'], 'desc')
  const dateUnemptys = orderPosts.filter((item) => item.date)
  const dateEmptys = orderPosts.filter((item) => !item.date)
  const result = dateUnemptys.concat(dateEmptys)
  return result
};

export const getPost = async (id: string) => {
  const filePaths = await fg(['posts/**/*.md'])
  const pathMaps = filePaths.map(item => ([getPostId(item), item]))
  const pathMap = pathMaps.find((item: string[]) => item[0] === id)

  if (!pathMap) return null
  const posts = await getPosts()
  const text = fs.readFileSync(pathMap[1], 'utf-8');
  const { data: { title, date }, content } = matter(text);
  const htmlContent = md.render(content) 
  const postId = pathMap[0]
  const index = _.findIndex(posts, (item: any) => item.id === postId)
  const prev: PostMeta | null = index > 0 ? posts[index - 1] : null
  const next: PostMeta | null = index < posts.length - 1 ? posts[index + 1] : null
  const result = {
    title: title || null,
    date: date ? dayjs(date).format('YYYY-MM-DD HH:mm') : '∞',
    htmlContent,
    prev,
    next
  }
  return JSON.parse(JSON.stringify(result))
}

export const getPostIds = async () => {
  const filePaths = await fg(['posts/**/*.md'])
  const result: string[] = []
  filePaths.forEach(item => {
    const id = getPostId(item)
    if (id === 'about') {
      return 
    }
    result.push(id)
  })
  return JSON.parse(JSON.stringify(result))
};

export const getCustomPost = async (id: string) => {
  const filePaths = await fg(['posts/**/*.md'])
  const idList = filePaths.map(p => ([getPostId(p), p]))
  const idMap = idList.find((item: string[]) => item[0] === id)

  if (!idMap) return null
  const text = fs.readFileSync(idMap[1], 'utf-8');
  const { data: { title, date }, content } = matter(text);
  const htmlContent = md.render(content) 
  const result = {
    title: title || null,
    date: date ? dayjs(date).format('YYYY-MM-DD HH:mm') : '∞',
    htmlContent,
  }
  return JSON.parse(JSON.stringify(result))
}


function getPostId(path: string) {
  const names = path.split(/(\\)|(\/)/)
  const fileName = names[names.length - 1]
  return fileName.replace(/\.md$/g, '')
}
